package cn.zyl.demo.undertow.config;

import cn.zyl.demo.undertow.handler.JspViewMethodReturnValueHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.ViewNameMethodReturnValueHandler;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * CustomWebConfig 类说明: 自定义 HandlerMethodReturnValueHandler 放到 HttpEntityMethodProcessor 之前
 *
 * @author z.y.l
 * @version v1.0
 * @date 2020-09-08
 */
@Configuration
public class CustomWebConfig extends WebMvcConfigurationSupport {
    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;
    @Bean
    public HandlerMethodReturnValueHandler customReturnValueHandler() {
        return new JspViewMethodReturnValueHandler();
    }
    @PostConstruct
    public void init() {
        System.out.println("++++++++++++++ CustomWebConfig");
        final List<HandlerMethodReturnValueHandler> originalHandlers = new ArrayList<>(Objects.requireNonNull(handlerAdapter.getReturnValueHandlers()));
        /* 在 HttpEntityMethodProcessor 之前添加自定义处理程序，以启用 JspViewMethodReturnValueHandler ！ */
        final int deferredPos = obtainValueHandlerPosition(originalHandlers);
        originalHandlers.add(deferredPos - 1, customReturnValueHandler());
        originalHandlers.forEach(handler -> System.out.println(handler.getClass().getSimpleName()));
        handlerAdapter.setReturnValueHandlers(originalHandlers);
    }
    private int obtainValueHandlerPosition(final List<HandlerMethodReturnValueHandler> originalHandlers) {
        HandlerMethodReturnValueHandler valueHandler;
        for (int i = 0; i < originalHandlers.size(); i++) {
            valueHandler = originalHandlers.get(i);
            if (ViewNameMethodReturnValueHandler.class.isAssignableFrom(valueHandler.getClass())) {
                return i;
            }
        }
        return -1;
    }
}
